import 'dart:math';

import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_models/jr_activity_model.dart';
import 'package:jet_rails/jr_app/jr_models/jr_comment_model.dart';
import 'package:jet_rails/jr_app/jr_views/jr_home/jr_home_controller.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_app_bar.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_blur_container.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_comment_widget.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_scaffold.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_snippet.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';

class JrActivityDetailView extends StatefulWidget {
  const JrActivityDetailView({
    super.key,
    required this.activityModel,
  });

  final JrActivityModel activityModel;

  @override
  State<JrActivityDetailView> createState() => _JrActivityDetailViewState();
}

class _JrActivityDetailViewState extends State<JrActivityDetailView> {
  JrHomeController controller = Get.find<JrHomeController>();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: JrScaffold(
        defaultTopPadding: false,
        appBar: JrAppBar(
          title: 'Event Detail',
          backgroundColor: Colors.transparent,
          showRailIcon: false,
          actions: [
            if (!JrServices.instance.isMe(widget.activityModel.author?.userId ?? ''))
              Container(
                height: 30.h,
                margin: EdgeInsets.only(right: 20.w, top: 7.h, bottom: 7.h),
                child: GestureDetector(
                  onTap: () {
                    if (widget.activityModel.author?.userId != null) {
                      JrSnippets.popMoreMenuDialog(widget.activityModel.author!.userId);
                    }
                  },
                  child: Image.asset(
                    'assets/webp/icon_more_option_action.webp',
                    height: 36.h,
                  ),
                ),
              )
          ],
        ),
        body: Stack(
          clipBehavior: Clip.none,
          children: [
            Positioned(top: 0, left: 0, right: 0, height: 280.h, child: buildPoster()),
            Positioned(bottom: 0, left: 0, right: 0, height: 565.h, child: buildContentPanel()),
            Positioned(bottom: 0, left: 0, right: 0, height: 90.h, child: buildInputWidget()),
          ],
        ),
      ),
    );
  }

  Widget buildPoster() {
    return SizedBox(
      height: 280.h,
      child: Swiper(
        loop: false,
        itemCount: widget.activityModel.content.length,
        itemBuilder: (BuildContext context, int index) {
          if (widget.activityModel.content.isNotEmpty) {
            return Image.asset(
              widget.activityModel.content.elementAt(index),
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.cover,
            );
          }
          return Container();
        },
      ),
    );
  }

  Widget buildContentPanel() {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        JrBlurContainer(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(topLeft: const Radius.circular(24), topRight: Radius.circular(24.r)),
            gradient: const LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [Color.fromRGBO(164, 110, 255, 0.6), Color.fromRGBO(164, 110, 255, 0.2)],
            ),
          ),
        ),
        Positioned(bottom: 0, left: 0, right: 0, height: 500.h, child: buildContent()),
        if (widget.activityModel.author?.avatar != null)
          Positioned(
            top: -28.h,
            left: 32.w,
            child: CircleAvatar(
              radius: 28.r,
              backgroundImage: NetworkImage(widget.activityModel.author?.avatar ?? ''),
            ),
          ),
        if (widget.activityModel.author?.nickname != null)
          Positioned(
            top: 31.h,
            left: 32.w,
            width: 170.w,
            child: Text(
              widget.activityModel.author?.nickname ?? '',
              style: TextStyle(fontSize: 14.sp, color: Colors.white),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        Positioned(
          top: -12.h,
          right: 32.w,
          child: StatefulBuilder(
            builder: (context, setState) => GestureDetector(
              onTap: () {
                controller.toggleLike(widget.activityModel);
                setState(() {});
              },
              child: Image.asset(
                widget.activityModel.likedByMe
                    ? 'assets/webp/icon_star_active.webp'
                    : 'assets/webp/icon_star_default.webp',
                width: 20.r,
                height: 20.r,
              ),
            ),
          ),
        ),
        if (widget.activityModel.attendedUser > 0)
          Positioned(
            top: 31.h,
            right: 32.w,
            child: Text(
              '${widget.activityModel.attendedUser} People attended',
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(color: Color(0xFFFC68FF)),
            ),
          ),
      ],
    );
  }

  Widget buildContent() {
    return SingleChildScrollView(
      child: Container(
        margin: EdgeInsets.only(left: 20.w, right: 20.w),
        child: Column(children: [
          buildInfoWidget(),
          Container(
            height: 16.h,
          ),
          buildCommentsWidget(),
          SizedBox(height: 90.h),
        ]),
      ),
    );
  }

  Widget buildInfoWidget() {
    return JrBlurContainer(
      margin: EdgeInsets.only(top: 10.h),
      padding: EdgeInsets.all(16.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(color: Colors.white24, offset: Offset(0, 0.5.r), blurRadius: 1.r),
        ],
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color.fromRGBO(227, 148, 255, 1), Color.fromRGBO(255, 81, 164, 1)],
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Team Name: ${widget.activityModel.teamName ?? ''}',
            style: TextStyle(color: Colors.white, fontSize: 16.sp),
          ),
          SizedBox(height: 16.h),
          Text(
            'Time: ${widget.activityModel.time ?? ''}',
            style: TextStyle(color: Colors.white.withOpacity(0.6), fontSize: 14.sp),
          ),
          SizedBox(height: 16.h),
          Text(
            'Place: ${widget.activityModel.place ?? ''}',
            style: TextStyle(color: Colors.white.withOpacity(0.6), fontSize: 14.sp),
          ),
          SizedBox(height: 16.h),
          Text(
            'Description: ${widget.activityModel.description ?? ''}',
            style: TextStyle(color: Colors.white.withOpacity(0.6), fontSize: 13.sp),
          ),
          SizedBox(height: 20.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (!JrServices.instance.isMe(widget.activityModel.author?.userId ?? ''))
                JrStyledButton(
                  text: widget.activityModel.joined ? 'Withdraw' : 'Participate',
                  onTap: () => Get.dialog(
                      Center(
                        child: Container(
                          height: 170.h,
                          width: 320.w,
                          padding: EdgeInsets.symmetric(horizontal: 24.h, vertical: 32.w),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10.r),
                              image: const DecorationImage(
                                  alignment: Alignment.bottomCenter,
                                  image: AssetImage('assets/webp/img_activity_widget_bg.webp'),
                                  fit: BoxFit.fitWidth)),
                          child: Column(
                            children: [
                              Text(
                                'Are you sure you want to ${widget.activityModel.joined ? 'withdraw from' : 'register for'} this event?',
                                style: const TextStyle(color: Colors.white),
                              ),
                              SizedBox(height: 24.h),
                              JrStyledButton(
                                  text: widget.activityModel.joined ? 'Withdraw' : 'Participate',
                                  onTap: () {
                                    final joined = widget.activityModel.joined;
                                    controller.toggleJoinStatus(widget.activityModel);
                                    setState(() {});
                                    Get.back();
                                    JrToast.show(joined ? 'Cancel success' : 'Successfully participated');
                                  })
                            ],
                          ),
                        ),
                      ),
                      transitionDuration: const Duration(milliseconds: 100)),
                )
            ],
          )
        ],
      ),
    );
  }

  Widget buildCommentsWidget() {
    //#A46EFF
    return StatefulBuilder(
      builder: (context, setState) => Column(
        children: widget.activityModel.commentList.map((comment) => JrCommentWidget(commentModel: comment)).toList(),
      ),
    );
  }

  Widget buildInputWidget() {
    return Container(
      height: 90.h,
      decoration: BoxDecoration(
        color: Colors.white30,
        borderRadius: const BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12)),
        boxShadow: [BoxShadow(color: Colors.grey.withOpacity(0.5), blurRadius: 10)],
      ),
      child: Row(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 20.w),
              decoration: BoxDecoration(
                color: const Color(0xFFF8F8F8),
                borderRadius: BorderRadius.circular(36.w),
              ),
              child: TextField(
                controller: _textEditingController,
                onSubmitted: (value) {
                  onClickSendBtn();
                },
                decoration: const InputDecoration(
                  hintText: 'Enter your ideas...',
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(left: 20, right: 20),
                ),
                maxLines: 1,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              onClickSendBtn();
            },
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16.w),
                color: const Color(0xFF404040),
              ),
              width: 62.w,
              height: 32.h,
              margin: EdgeInsets.only(left: 20.w, right: 20.w),
              child: Text(
                'Send',
                style: TextStyle(color: Colors.white, fontSize: 16.sp),
              ),
            ),
          ),
        ],
      ),
    );
  }

  final TextEditingController _textEditingController = TextEditingController();

  void onClickSendBtn() async {
    try {
      FocusScope.of(context).unfocus();
      EasyLoading.show();
      await Future.delayed(Duration(milliseconds: 1000 + Random().nextInt(1000)));
      String content = _textEditingController.text;
      JrCommentModel comment = JrCommentModel(
        avatar: JrServices.instance.loginUser.value.getAvatarUrl,
        nickname: JrServices.instance.loginUser.value.nickname,
        content: content,
      );
      widget.activityModel.commentList.insert(0, comment);
      setState(() {});
      await JrServices.instance.saveActivity();
      await controller.refreshActivityList();
      _textEditingController.text = '';
    } finally {
      EasyLoading.dismiss();
    }
  }
}
